package com.connector.server.handler;

import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Iterator;
import com.connector.base.connection.channel.SocketChannel;
import java.util.concurrent.ConcurrentMap;
import com.connector.base.connection.impl.NettyConnection;
import java.util.HashMap;
import com.connector.base.message.model.ChatMessage;
import java.util.Objects;
import com.connector.base.connection.impl.LocalConnectionRegistry;
import com.connector.base.connection.SessionContext;
import com.connector.server.util.PushMsgUtil;
import com.alibaba.fastjson.JSON;
import com.connector.server.util.SessionContextUtil;
import io.netty.channel.ChannelFutureListener;
import com.connector.base.message.model.BaseMessage;
import org.apache.commons.lang3.StringUtils;
import com.connector.base.utils.ErrorCode;
import com.google.common.base.Strings;
import com.connector.base.connection.Connection;
import com.connector.base.protocol.Packet;
import com.connector.server.InstantServer;
import com.connector.base.connection.session.ResuableSessionManager;
import org.slf4j.Logger;
import com.connector.base.message.model.HandshakeMessage;
import com.connector.base.handler.BaseMessageHandler;

public class HandshakeHandler extends BaseMessageHandler<HandshakeMessage>
{
    private static final Logger log;
    private final ResuableSessionManager resuableSessionManager;
    
    public HandshakeHandler(final InstantServer instantServer) {
        this.resuableSessionManager = instantServer.getResuableSessionManager();
    }
    
    public HandshakeMessage decode(final Packet packet, final Connection connection) {
        return new HandshakeMessage(packet, connection);
    }
    
    public void handle(final HandshakeMessage message) {
        if (Strings.isNullOrEmpty(message.getDeviceId())) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "没有找到设备标识！").close();
            HandshakeHandler.log.error("handshake failure, message={}, conn={}", (Object)message, (Object)message.getConnection());
            return;
        }
        final SessionContext context = message.getConnection().getSessionContext();
        if (StringUtils.isEmpty((CharSequence)message.getUserId())) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.UNKNOWN).buildResult("Param invalid", "用户id为空,握手失败！").close();
        }
        try {
            BaseMessage.buildSuccessResponse(message.getConnection()).channelSend((ChannelFutureListener)null);
            final String mobile = message.getMobile();
            if (StringUtils.isEmpty((CharSequence)mobile) || mobile.equals("1")) {
                message.setMobile("1");
            }
            else {
                message.setMobile("2");
            }
            final Connection connection = message.getConnection();
            connection.setSessionContext(SessionContextUtil.buildSessionContext(message));
            HandshakeHandler.log.info("握手成功,handshakeMessage:{}", (Object)JSON.toJSONString((Object)message));
            this.mobildLogin(message);
            PushMsgUtil.pushHandshakeMsg(message.getUserId());
        }
        catch (Throwable e) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.UNKNOWN).buildResult(e.getMessage(), "握手失败！").close();
            HandshakeHandler.log.error("chat failure!", e);
        }
    }
    
    private void mobildLogin(final HandshakeMessage message) {
        final ConcurrentMap<SocketChannel, Connection> cons = (ConcurrentMap<SocketChannel, Connection>)LocalConnectionRegistry.getConnections();
        final String userId = message.getUserId();
        for (final Connection c : cons.values()) {
            final String uId = c.getSessionContext().getUserId();
            if (userId.equals(uId) && !Objects.isNull(message.getCid()) && !message.getCid().equals(c.getSessionContext().getCid())) {
                final ChatMessage chatMessage = new ChatMessage();
                chatMessage.setUserId(userId);
                final Map<String, Object> map = new HashMap<String, Object>();
                map.put("type", "600");
                map.put("text", "该账号已在另一台设备上登录");
                map.put("params", null);
                chatMessage.setBody(JSON.toJSONString((Object)map));
                chatMessage.setType("4");
                chatMessage.setReceiver(userId);
                final String msgJson = JSON.toJSONString((Object)chatMessage);
                final Packet packet = ChatMessage.buildPacket(msgJson);
                if (!(c instanceof NettyConnection)) {
                    continue;
                }
                c.channelSend((Object)packet);
            }
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)HandshakeHandler.class);
    }
}
